﻿using FireChat.Server.Database.Manager;
using FireChat.Server.Session.Receiver;
using FireChat.Server.Session.Remote;
using FireChat.Share.Web.Actions;
using FireChat.Share.Web.Package;
using FireChat.Share.Web.Util;

namespace FireChat.Server.Session.Actions;


/// <summary>
/// 服务器动作执行过程
/// </summary>
internal abstract class ServerAction : IServerAction
{
    /// <summary>
    /// 对应的动作类型
    /// </summary>
    public abstract ServertActions Type { get; }

    /// <summary>
    /// 是否验证账户令牌 默认验证
    /// </summary>
    public virtual bool IsVerifyAccountToken { get; } = true;

    /// <summary>
    /// 执行过程
    /// </summary>
    /// <param name="receiver">包接收器</param>
    /// <returns>响应内容</returns>
    public virtual ServerPackage Excute(PackageReceiver receiver)
    {
        if (IsVerifyAccountToken && !receiver.Session.VerifyAccountToken())
        {
            return receiver.ReplyFailureAsync("账户未登录");
        }

        return Excute(receiver);
    }

    /// <summary>
    /// 执行过程
    /// </summary>
    /// <param name="receiver">包接收器</param>
    /// <param name="query">请求的数据</param>
    /// <returns>响应内容</returns>
    protected abstract ServerPackage ActionExcute(PackageReceiver receiver);
}

/// <summary>
/// 服务器动作执行过程
/// </summary>
internal abstract class ServerAction<T> : IServerAction where T : class
{
    /// <summary>
    /// 对应的动作类型
    /// </summary>
    public abstract ServertActions Type { get; }

    /// <summary>
    /// 是否验证账户令牌  默认验证 (就是验证账户是否登录
    /// </summary>
    public virtual bool IsVerifyAccountToken { get; } = true;


    /// <summary>
    /// 执行过程
    /// </summary>
    /// <param name="receiver">包接收器</param>
    /// <returns>响应内容</returns>
    public ServerPackage Excute(PackageReceiver receiver)
    {
        if (IsVerifyAccountToken && !receiver.Session.VerifyAccountToken())
        {
            return receiver.ReplyFailureAsync("账户未登录");
        }

        if (receiver.Package.GetDataInstance<T>() is not T query)
        {
            return receiver.ReplyFailureAsync("请求数据异常");
        }

        return ActionExcute(receiver, query);
    }

    /// <summary>
    /// 执行过程
    /// </summary>
    /// <param name="receiver">包接收器</param>
    /// <param name="query">请求的数据</param>
    /// <returns>响应内容</returns>
    protected abstract ServerPackage ActionExcute(PackageReceiver receiver, T query);
}
